package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/dashboard/users")
public class UserController {

    private final UserService userService;
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public UserController(UserService userService, UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @GetMapping
    public String listUsers(Model model, @RequestParam(required = false) String search) {
        List<User> users;
        
        if (search != null && !search.isEmpty()) {
            // 简单的搜索功能，根据用户名或邮箱查找
            users = userRepository.findByUsernameContainingOrEmailContainingOrFullNameContaining(search, search, search);
        } else {
            users = userRepository.findAll();
        }
        
        model.addAttribute("users", users);
        model.addAttribute("user", new User());
        model.addAttribute("search", search);
        model.addAttribute("user", userService.getCurrentUser());
        return "dashboard/users/list";
    }

    @PostMapping("/create")
    public String createUser(@ModelAttribute User user, RedirectAttributes redirectAttributes) {
        try {
            // 检查用户名是否已存在
            if (userService.isUsernameExists(user.getUsername())) {
                redirectAttributes.addFlashAttribute("errorMessage", "用户名已存在");
                return "redirect:/dashboard/users";
            }
            
            // 检查邮箱是否已存在
            if (userService.isEmailExists(user.getEmail())) {
                redirectAttributes.addFlashAttribute("errorMessage", "邮箱已存在");
                return "redirect:/dashboard/users";
            }
            
            // 对密码进行加密
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            
            // 设置创建时间
            user.setCreatedAt(LocalDateTime.now());
            
            // 保存用户
            userRepository.save(user);
            redirectAttributes.addFlashAttribute("successMessage", "用户创建成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        return "redirect:/dashboard/users";
    }

    @GetMapping("/edit/{id}")
    public String editUserForm(@PathVariable Long id, Model model) {
        User userToEdit = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        model.addAttribute("user", userToEdit);
        model.addAttribute("userActivities", List.of()); // 这里可以添加用户活动记录
        model.addAttribute("currentUser", userService.getCurrentUser());
        return "dashboard/users/edit";
    }

    @PostMapping("/edit/{id}")
    public String updateUser(@PathVariable Long id, 
                            @ModelAttribute User userDetails,
                            @RequestParam(required = false) MultipartFile profileImageFile,
                            RedirectAttributes redirectAttributes) {
        try {
            User existingUser = userRepository.findById(id)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 检查邮箱是否已被其他用户使用
            userRepository.findByEmail(userDetails.getEmail()).ifPresent(u -> {
                if (!u.getId().equals(id)) {
                    throw new RuntimeException("邮箱已被其他用户使用");
                }
            });
            
            // 更新用户信息
            existingUser.setEmail(userDetails.getEmail());
            existingUser.setFullName(userDetails.getFullName());
            existingUser.setRole(userDetails.getRole());
            existingUser.setEnabled(userDetails.isEnabled());
            
            // 处理头像上传
            if (profileImageFile != null && !profileImageFile.isEmpty()) {
                try {
                    String uploadsDir = "./uploads/profiles/";
                    Path uploadsPath = Paths.get(uploadsDir);
                    if (!Files.exists(uploadsPath)) {
                        Files.createDirectories(uploadsPath);
                    }
                    
                    // 生成唯一文件名
                    String fileName = UUID.randomUUID().toString() + "-" + profileImageFile.getOriginalFilename();
                    Path filePath = Paths.get(uploadsDir + fileName);
                    Files.write(filePath, profileImageFile.getBytes());
                    
                    // 更新头像路径
                    existingUser.setProfileImage("/uploads/profiles/" + fileName);
                } catch (IOException e) {
                    redirectAttributes.addFlashAttribute("errorMessage", "头像上传失败：" + e.getMessage());
                }
            }
            
            userRepository.save(existingUser);
            redirectAttributes.addFlashAttribute("successMessage", "用户信息更新成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        return "redirect:/dashboard/users";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            // 检查是否是当前登录用户
            User currentUser = userService.getCurrentUser();
            if (currentUser.getId().equals(id)) {
                redirectAttributes.addFlashAttribute("errorMessage", "不能删除当前登录用户");
                return "redirect:/dashboard/users";
            }
            
            userRepository.deleteById(id);
            redirectAttributes.addFlashAttribute("successMessage", "用户已删除");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "删除用户失败：" + e.getMessage());
        }
        return "redirect:/dashboard/users";
    }

    @GetMapping("/enable/{id}")
    public String enableUser(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            User user = userRepository.findById(id)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            user.setEnabled(true);
            userRepository.save(user);
            redirectAttributes.addFlashAttribute("successMessage", "用户已启用");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        return "redirect:/dashboard/users";
    }

    @GetMapping("/disable/{id}")
    public String disableUser(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            // 检查是否是当前登录用户
            User currentUser = userService.getCurrentUser();
            if (currentUser.getId().equals(id)) {
                redirectAttributes.addFlashAttribute("errorMessage", "不能禁用当前登录用户");
                return "redirect:/dashboard/users";
            }
            
            User user = userRepository.findById(id)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            user.setEnabled(false);
            userRepository.save(user);
            redirectAttributes.addFlashAttribute("successMessage", "用户已禁用");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        return "redirect:/dashboard/users";
    }

    @GetMapping("/reset-password/{id}")
    public String resetPassword(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            User user = userRepository.findById(id)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 设置一个默认的密码
            String defaultPassword = "Password123";
            user.setPassword(passwordEncoder.encode(defaultPassword));
            userRepository.save(user);
            
            redirectAttributes.addFlashAttribute("successMessage", "用户密码已重置为：" + defaultPassword);
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        return "redirect:/dashboard/users";
    }
} 